import { defineComponent, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import {
  ElButton,
  ElMessage,
  ElLink,
  ElMessageBox,
  ElSpace,
  ElImage,
  ElRow,
  ElCol
} from 'element-plus'
import type { LampModalType, LoopTable } from './typings'
import type { TableColumnProps } from '~/components/ProSaasTable/typings'
import ProSaasTable from '~/components/ProSaasTable'
import styles from '../../index.module.scss' /** 样式 */
import AliIcon from '../../../../components/AliIocn' /** 阿里巴巴图标库**/
import DimModel from '../../components/dimModel'
import useVuexGetters from '~/hooks/useVuexGetters'
import useWebsocket from '~/hooks/useWebsocket'
import NoticeMes from '../../components/noticeMes'

import callDataSrc from '~/assets/singleLamp/callData.png'
import dimLightSrc from '~/assets/singleLamp/dim.png'
import openLightSrc from '~/assets/singleLamp/open.png'
import closeLightSrc from '~/assets/singleLamp/close.png'
import callTimeSrc from '~/assets/singleLamp/callTime.png'
import timingSrc from '~/assets/singleLamp/timing.png'
import clearSrc from '~/assets/singleLamp/clear.png'
import resettingSrc from '~/assets/singleLamp/resetting.png'

export default defineComponent({
  props: ['cancel'],
  setup(props, { expose }) {
    const store = useStore()
    const state = reactive<LampModalType>({
      dimVisible: false
    })
    const dimModelRef = ref()
    const userState = useVuexGetters('user', ['token'])
    const webSocketRef = useWebsocket('/websocket/protocol/lampctrl', {
      // // 接收数据回调
      onmessage: () => {}
    })
    const noticeRef = ref()
    const columns: TableColumnProps<LoopTable>[] = [
      {
        label: '回路',
        prop: 'num',
        minWidth: 50,
        align: 'center',
        unFixed: true,
        showOverflowTooltip: true
      },
      {
        label: '开关',
        prop: 'switchStatus',
        minWidth: 50,
        align: 'center',
        showOverflowTooltip: true,
        render: ({ row }) => (
          <div
            class={styles.lightIcon}
            style={
              row.switchStatus === '1' ? 'background-color: #f85151;' : 'background-color: #a1a1a1'
            }
          ></div>
        )
      },
      {
        label: '电压',
        prop: 'dcVoltage',
        minWidth: 100,
        align: 'center',
        showOverflowTooltip: true
      },
      {
        label: '电流',
        prop: 'dcCurrent',
        minWidth: 100,
        align: 'center',
        showOverflowTooltip: true
      },
      {
        label: '调光',
        prop: 'dimmingLevel',
        minWidth: 100,
        align: 'center',
        unFixed: true,
        showOverflowTooltip: true,
        disabled: true
      },
      {
        label: '有功功率',
        prop: 'activePower',
        minWidth: 100,
        align: 'center',
        unFixed: true,
        showOverflowTooltip: true,
        disabled: true
      },
      {
        label: '漏电流',
        prop: 'leakageCurrent',
        minWidth: 80,
        align: 'center',
        unFixed: true,
        showOverflowTooltip: true,
        disabled: true
      },
      {
        label: '额定功率',
        prop: 'ratedPower',
        minWidth: 100,
        align: 'center',
        showOverflowTooltip: true
      },
      {
        label: '方位',
        prop: 'position',
        minWidth: 100,
        align: 'center',
        showOverflowTooltip: true,
        render: ({ row }) => <div>{filterPosition(row.position)}</div>
      },
      {
        label: '操作',
        prop: 'option',
        minWidth: 100,
        align: 'center',
        fixed: 'right',
        // unFixed: true,
        disabled: true,
        render: ({ row }) => (
          <ElSpace>
            <ElLink type="primary" onClick={() => dimModelChange(row)}>
              <AliIcon type="icon-chakan" />
              &nbsp; 调光
            </ElLink>
          </ElSpace>
        )
      }
    ]
    const filterPosition = (position?: string) => {
      switch (position) {
        case '0':
          return '主道'
        case '1':
          return '辅道'
        default:
          return position
      }
    }
    const open = async (data: any) => {
      const id = data.id
      const res = await store.dispatch('singleLamp/DeviceSimpleMes', { id })
      if (res.code === 200) {
        state.lampInfo = res.data
      }
    }
    // 操作指令
    const handleCommand = (type?: number) => {
      const tokenValue = userState.token.value
      let text = ''
      let commandCodeValue = ''
      let title = ''
      if (type === 1) {
        text = '确认下发开灯命令？'
        commandCodeValue = '004'
        title = '开灯'
      } else if (type === 2) {
        text = '确认下发关灯命令？'
        commandCodeValue = '004'
        title = '关灯'
      } else if (type === 3) {
        text = '确认下发调光命令？'
        commandCodeValue = '004'
        title = '调光'
      } else if (type === 4) {
        text = '确认下发召测工况命令？'
        commandCodeValue = '006'
        title = '召测工况'
      } else if (type === 5) {
        text = '确认下发召测时钟命令？'
        commandCodeValue = '007'
        title = '召测时钟'
      } else if (type === 6) {
        text = '确认下发清除漏电保护命令？'
        title = '清除漏电保护'
        commandCodeValue = '009'
      } else if (type === 7) {
        text = '确认下发单灯复位命令？'
        title = '单灯复位'
        commandCodeValue = '012'
      } else if (type === 8) {
        text = '确认下发设备校时命令？'
        commandCodeValue = '008'
        title = '设备校时'
      }
      const websockParams = {
        token: tokenValue,
        deviceId: state.lampInfo?.id,
        commandCode: commandCodeValue
      }
      ElMessageBox({
        title: '确认提示',
        message: (
          <section class={styles['delete-confirm-box']}>
            {<p class="delete-title">{text}</p>}
          </section>
        ),
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--primary is-plain',
        closeOnClickModal: false, // 点遮罩层不关弹窗
        draggable: true // 可拖拽
      })
        .then(async () => {
          if (type === 3) {
            dimModelChange()
          } else {
            handleConmandAjax(type)
            webSocketRef.value!.send(JSON.stringify(websockParams))
            // websocket请求
            noticeRef.value.initMes({
              deviceId: state.lampInfo?.id,
              commandCode: commandCodeValue,
              token: userState.token.value,
              title,
              key: commandCodeValue,
              arrStr: state.lampInfo?.code,
              callBack: () => {}
            })
          }
        })
        .catch(() => {})
    }
    const handleConmandAjax = async (type?: number) => {
      if (type === 1) {
        // 开灯
        await store
          .dispatch('singleLamp/SinglelampSwitch', { lampNodeId: state.lampInfo?.id, opr: 1 })
          .then(async (result) => {
            if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
          })
      } else if (type === 2) {
        // 关灯
        await store
          .dispatch('singleLamp/SinglelampSwitch', { lampNodeId: state.lampInfo?.id, opr: 0 })
          .then(async (result) => {
            if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
          })
      } else if (type === 4) {
        // 召测工况
        await store
          .dispatch('singleLamp/CallLampWorkData', { lampNodeId: state.lampInfo?.id })
          .then(async (result) => {
            if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
          })
      } else if (type === 5) {
        // 召测时钟
        await store
          .dispatch('singleLamp/CallLampTime', { lampNodeId: state.lampInfo?.id })
          .then(async (result) => {
            if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
          })
      } else if (type === 6) {
        // 解除漏电保护
        await store
          .dispatch('singleLamp/LampNodeCleanProtect', { lampNodeId: state.lampInfo?.id })
          .then(async (result) => {
            if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
          })
      } else if (type === 7) {
        // 单灯复位
        await store
          .dispatch('singleLamp/LampResetting', { lampNodeId: state.lampInfo?.id })
          .then(async (result) => {
            if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
          })
      } else if (type === 8) {
        // 设备校时
        await store
          .dispatch('singleLamp/LampNodeTimeSyncSet', { lampNodeId: state.lampInfo?.id })
          .then(async (result) => {
            if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
          })
      }
    }

    // 调光
    const dimLight = async () => {
      const dimNum = dimModelRef.value.ruleForm.dimNum
      const websockParams = {
        token: userState.token.value,
        deviceId: state.lampInfo?.id,
        commandCode: ''
      }
      let title = ''
      if (state.loop) {
        // 针对回路
        websockParams.commandCode = '005'
        title = '单回路调光'
        const res = await store.dispatch('singleLamp/SinglelampDimLoop', {
          lampNodeId: state.lampInfo?.id,
          dim: dimNum,
          loop: state.loop
        })
        if (res.code === 200) dimModelChange()
      } else {
        // 所有回路
        websockParams.commandCode = '004'
        title = '全回路调光'
        const res = await store.dispatch('singleLamp/SinglelampDim', {
          lampNodeId: state.lampInfo?.id,
          dim: dimNum
        })
        if (res.code === 200) dimModelChange()
      }
      webSocketRef.value!.send(JSON.stringify(websockParams))

      noticeRef.value.initMes({
        deviceId: state.lampInfo?.id,
        commandCode: websockParams.commandCode,
        token: userState.token.value,
        title,
        key: websockParams.commandCode,
        arrStr: state.lampInfo?.code,
        callBack: () => {}
      })
    }
    const dimModelChange = (data?: any) => {
      state.dimVisible = !state.dimVisible
      state.loop = data?.num
    }

    const swInitFun = (data?: any) => {
      if (data.data.status === 2) {
        noticeRef.value.stateFun({
          key: data.commandCode,
          state: 'error',
          errText: data.data.message || '命令下发失败！'
        })
        return false
      }
      // 单个回路
      if (data.data.status === 1)
        noticeRef.value.stateFun({
          key: data.commandCode,
          id: ''
        })
    }

    const filterOnline = (type: number) => {
      switch (type) {
        case 1:
          return '（在线）'
        case 2:
          return '（离线）'
        default:
          return ''
      }
    }
    const filterRun = (type: number) => {
      switch (type) {
        case 1:
          return '（正常）'
        case 2:
          return '（故障）'
        default:
          return ''
      }
    }
    // 离开前 先断开websocket连接
    onUnmounted(() => {
      webSocketRef.value?.close()
    })

    onMounted(() => {
      window.swInitFun = swInitFun
    })

    expose({ open })
    return () => (
      <section>
        <div class={styles.lamppostRight}>
          <div class={styles.lampTitle}>
            <div class={styles.lineTxt}>
              {state.lampInfo?.name}
              <span style={state.lampInfo?.onlineState === 1 ? 'color:#50fb4a' : 'color:#c3c3c3'}>
                {filterOnline(state.lampInfo?.onlineState)}
              </span>
            </div>
            <div>
              <span style={state.lampInfo?.runStatus === 1 ? 'color:#50fb4a' : 'color:#f85151'}>
                {filterRun(state.lampInfo?.runStatus)}
              </span>
              <ElLink type="primary" underline={false} onClick={props.cancel}>
                <AliIcon type="icon-danchuang-guanbi" color="#fff" />
              </ElLink>
            </div>
          </div>
          <div class={styles.content}>
            <div class={styles.option}>
              <ElButton onClick={() => handleCommand(1)}>
                <ElImage src={openLightSrc} style="margin-right:4px" />
                开灯
              </ElButton>
              <ElButton onClick={() => handleCommand(2)}>
                <ElImage src={closeLightSrc} style="margin-right:4px" />
                关灯
              </ElButton>
              <ElButton onClick={() => handleCommand(3)}>
                <ElImage src={dimLightSrc} style="margin-right:4px" />
                调光
              </ElButton>
              <ElButton onClick={() => handleCommand(4)}>
                <ElImage src={callDataSrc} style="margin-right:4px" />
                召测工况
              </ElButton>
              <ElButton onClick={() => handleCommand(5)}>
                <ElImage src={callTimeSrc} style="margin-right:4px" />
                召测时钟
              </ElButton>
            </div>
            <div class={styles.option}>
              <ElButton onClick={() => handleCommand(6)}>
                <ElImage src={clearSrc} style="margin-right:4px" />
                清除漏电保护
              </ElButton>
              <ElButton onClick={() => handleCommand(7)}>
                <ElImage src={resettingSrc} style="margin-right:4px" />
                单灯复位
              </ElButton>
              <ElButton onClick={() => handleCommand(8)}>
                <ElImage src={timingSrc} style="margin-right:4px" />
                设备校时
              </ElButton>
            </div>
            <div style="margin-bottom:10px">
              <ElRow>
                <ElCol span={12}>单灯编号：{state.lampInfo?.code}</ElCol>
                <ElCol span={12}>所属灯杆：{state.lampInfo?.lampPostName}</ElCol>
              </ElRow>
              <ElRow>
                <ElCol span={12}>所属品牌：{state.lampInfo?.brandName}</ElCol>
                <ElCol span={12}>所属型号：{state.lampInfo?.modelName}</ElCol>
              </ElRow>
            </div>
            <ProSaasTable<LoopTable>
              columns={columns}
              data={state.lampInfo?.workinfoVOList || []}
              needPagination={false}
            />
          </div>
        </div>
        {state.dimVisible && (
          <DimModel ref={dimModelRef} onSubmitForm={dimLight} cancel={dimModelChange} />
        )}
        <NoticeMes ref={noticeRef} />
      </section>
    )
  }
})
